// pages/test/test.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';

const app = getApp()
var correctNum = 0;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    startClock: false,  //开始倒计时
    dataOK: false,  //数据准备好了
    grade: 0,  //选择的年级
    num: 5,   //题目总数
    timeout: 0, //倒计时（ms）
    timeData: null,
    typeInfo: [
      {
        label: '未分类',
        eg: '暂无'
      },
      {
        label: '整数加减法',
        eg: '16 + 28 = 44'
      },
      {
        label: '整数乘除法',
        eg: '22 × 2 = 11'
      },
      {
        label: '小数加减法',
        eg: '1.6 + 0.4 = 2.0'
      },
      {
        label: '小数乘除法',
        eg: '1.2 ÷ 2.0 = 0.6'
      },
      {
        label: '小数比大小',
        eg: '1.56 < 1.7'
      },
      {
        label: '分数加减法',
        eg: '1/2 - 1/3 = 1/6'
      },
      {
        label: '分数乘除法',
        eg: '1/3 ÷ 1/2 = 2/3'
      },
      {
        label: '分数比大小',
        eg: '1/3 < 1/2'
      },
      {
        label: '四则运算',
        eg: '1+2*3=7'
      },
    ],
    radio: ['0'],   //单选框选项
    r: ['⚪', '<', '>', '='],
    ansIn: [''], //用户输入
    validate: false, //是否校检答案
    correct: [true], //是否正确
    collect: [false],  //题目是否被收藏
    isChecking: false, //是否在检查中
    correctNum: 0,  //正确个数
    problems: []  //问题数组（由ks-api得来）
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    correctNum = 0;
    this.setData({
      grade: app.globalData.grade,
      num: parseInt(options.num),
      timeout: parseInt(options.minutes) * 60 * 1000,
    })
    //请求题目
    this.getExams(this.data.num);
    //初始化
    for (var i = 0; i < this.data.num; i++) {
      this.setData({
        [`ansIn[${i}]`]: '',
        [`radio[${i}]`]: '0',
        validate: false,
        [`correct[${i}]`]: true,
        [`collect[${i}]`]: false,
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   * 要将所有收藏上传服务端
   */
  onUnload: function () {
    var collections = {
      env: 'test',
      openid: app.globalData.openid,
      ord4cancel: [],
      num: 0,
      details: []
    }
    for (let i = 0; i < this.data.num; i++) {
      if (this.data.collect[i]) {
        let prob = this.data.problems[i];
        prob.opt_usr = parseInt(this.data.radio[i]);
        prob.ans_usr = this.data.ansIn[i];
        collections.details.push(prob);
        collections.num++;
      }
    }
    if (collections.num == 0) { return; }
    //调用ks-api收藏题目
    wx.cloud.callContainer({
      config: {
        env: "prod-6gmuxgtca5913e7c"
      },
      path: "/collections",
      header: {
        'X-WX-SERVICE': "ks-api",
        'content-type': "application/json"
      },
      method: "POST",
      data: collections,
      success: function (res) {
        if (res.statusCode != 200) {
          Notify({
            type: 'danger',
            message: '收藏上传失败。'
          })
        }
        Notify({
          type: 'success',
          message: '收藏上传成功！'
        })
      },
      failed: function (res) {
        Notify({
          type: 'danger',
          message: '收藏上传失败。'
        })
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 复选框逻辑
   */
  onChangeRadio(event) {
    if (this.data.validate) { return; }  //检查后禁用单选框
    this.setData({
      [`radio[${event.currentTarget.dataset.id}]`]: event.detail,
    });
  },

  onClickRadio(event) {
    if (this.data.validate) { return; }  //检查后禁用单选框
    const { name } = event.currentTarget.dataset;
    this.setData({
      [`radio[${event.currentTarget.dataset.id}]`]: name,
    });
  },

  /**
   * 用户点击检查，检查答案是否正确并显示正确答案
   */
  onValidate() {
    if (this.data.validate) {
      wx.navigateBack({
        delta: 1,
      })  //再次点击，返回主页
      return;
    }
    this.setData({
      isChecking: true
    })
    for (var i = 0; i < this.data.num; i++) {
      let problem = this.data.problems[i];
      if (problem.type == 5 || problem.type == 8) {
        //检查选择题
        let opt_usr = parseInt(this.data.radio[i]);
        this.setData({
          [`ansIn[${i}]`]: problem.formula.replace('⚪', this.data.r[opt_usr]),
          [`correct[${i}]`]: ((opt_usr == problem.option) ? true : false)
        })
      } else {
        this.setData({
          [`correct[${i}]`]: ((this.data.ansIn[i] == problem.answer) ? true : false)
        })
      }
      if (this.data.correct[i]) { //正确计数
        correctNum++;
      }
      this.setData({
        isChecking: false,
        validate: true,
        correctNum: correctNum
      })  //切换检查态
      Notify({
        type: "primary",
        message: '做对' + correctNum + '题'
      })
    }
  },
  /**
   * 获取练考试习题
   */
  getExams(num) {
    let that = this
    //调用ks-api获取题目
    wx.cloud.callContainer({
      config: {
        env: "prod-6gmuxgtca5913e7c"
      },
      path: "/problems",
      header: {
        'X-WX-SERVICE': "ks-api",
        'content-type': "application/json"
      },
      method: "GET",
      data: {
        env: 'test',
        grade: this.data.grade,
        num: num
      },
      success: function (res) {
        if (res.statusCode != 200) {
          Dialog.confirm({
            title: '加载失败',
            message: '题目不翼而飞了呢，请检查网络连接。',
          })
            .then(() => {
              // on confirm
              wx.navigateBack({
                delta: 1,
              })
            })
        } else {
          that.setData({
            [`problems`]: res.data.details,
            dataOK: true,
            startClock: true
          })
        }
      },
      failed: function (res) {
        Dialog.confirm({
          title: '加载失败',
          message: '题目不翼而飞了呢，请检查网络连接。',
        })
          .then(() => {
            // on confirm
            wx.navigateBack({
              delta: 1,
            })
          })
      }
    })
  },

  /**
   * 输入答案触发，更新this.data.ansIn
   */
  onInput(event) {
    let id = event.currentTarget.dataset.id;
    this.setData({
      [`ansIn[${id}]`]: event.detail
    })
  },

  /**
   * 用户收藏题目
   */
  onCollect(event) {
    let id = event.currentTarget.dataset.id;
    let isCollected = this.data.collect[id]
    if (isCollected) {
      Notify({
        background: '#FFFFFF',
        color: '#000000',
        message: '取消收藏 ×',
        duration: 1000
      })
    } else {
      Notify({
        background: '#fffe02',
        color: '#000000',
        message: '收藏成功 √',
        duration: 1000
      })
    }
    this.setData({
      [`collect[${id}]`]: !isCollected
    })
  },

  /**
   * 倒计时时间改变
   */
  onChangeTime(event) {
    this.setData({
      timeData: event.detail
    })
  },
  /**
   * 到时
   */
  onTimeout() {
    Notify('考试时间结束！');
    this.onValidate();
  }
})